package page.actionPage;

import com.alibaba.fastjson2.JSONObject;
import javafx.embed.swing.SwingFXUtils;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Paint;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import org.sikuli.script.Image;
import org.sikuli.script.Screen;
import page.BasePage;
import utils.ControllerUtils;
import utils.DBUtils;
import utils.GlobalVar;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Base64;

import static javafx.scene.paint.Color.TRANSPARENT;
import static utils.Constant.ACTION.IMAGE_BASE64;

public class FindImgBasePageController extends BasePage {
    @FXML
    private Button imgCapture;
    @FXML
    private ImageView imgView;

    private double dragStartX;
    private double dragStartY;
    private double dragEndX;
    private double dragEndY;
    private javafx.scene.shape.Rectangle selectRec;
    private BufferedImage findGraph;


    public static Image getImg(JSONObject data) {
        BufferedImage img = base64StringToImg(data.getString(IMAGE_BASE64));
        return new Image(img);
    }

    public static BufferedImage base64StringToImg(final String base64String) {
        try {
            return ImageIO.read(new ByteArrayInputStream(Base64.getDecoder().decode(base64String)));
        } catch (final IOException ioe) {
            throw new UncheckedIOException(ioe);
        }
    }

    public void selectArea() {
        // 最小化 action 窗口
        ((Stage) root.getScene().getWindow()).setIconified(true);
        // 最小化主窗口
        GlobalVar.getMainStage().setIconified(true);
        AnchorPane anchorPane = new AnchorPane();
        anchorPane.setStyle("-fx-background-color:#B5B5B522");
        Stage stage = ControllerUtils.createStage(anchorPane);
        stage.getScene().setFill(Paint.valueOf("#ffffff00"));
        // 全屏
        stage.setFullScreen(true);
        // stage 透明
        stage.initStyle(StageStyle.TRANSPARENT);
        // 全屏时不提示文字
        stage.setFullScreenExitHint("");
        stage.show();
        // esc 退出截图
        stage.getScene().setOnKeyPressed(keyEvent -> {
            if (keyEvent.getCode() == KeyCode.ESCAPE) {
                stage.close();
                // 还原 action 窗口
                ((Stage) root.getScene().getWindow()).setIconified(false);
                // 还原主窗口
                GlobalVar.getMainStage().setIconified(false);
            }
        });
        drag(anchorPane);

    }

    /*
     * @Author Dongle
     * @Description 保存图片数据到数据库
     * @Date 19:10 2023/1/27
     *
     **/
    public void saveImageInDB(DBUtils db) {
        if (findGraph != null) {
            db.saveInData(IMAGE_BASE64, imgToBase64String(findGraph));
        }
    }

    public void initAction(BasePage basePage) {
        BufferedImage bufferedImage;
        String imageBase64 = (String) basePage.db.getDataOrDefault(IMAGE_BASE64, "");
        if (!imageBase64.equals("")) {
            bufferedImage = base64StringToImg(imageBase64);
            findGraph = bufferedImage;
            imgView.setImage(SwingFXUtils.toFXImage(bufferedImage, null));
        }
        imgCapture.setOnMouseClicked(mouseEvent -> selectArea());
    }

    public void drag(AnchorPane anchorPane) {
        anchorPane.setOnMousePressed(mouseEvent -> {
            anchorPane.getChildren().clear();
            selectRec = new javafx.scene.shape.Rectangle();
            selectRec.setFill(TRANSPARENT);
            selectRec.setStroke(Paint.valueOf("#CD3700"));
            selectRec.setStrokeWidth(2);
//            selectRec.setBackground(null);
//            selectRec.setBorder(new Border(new BorderStroke(Paint.valueOf("#CD3700"), BorderStrokeStyle.SOLID, null, new BorderWidths(selectBoardWidth))));
            anchorPane.getChildren().add(selectRec);
            double x = mouseEvent.getX();
            double y = mouseEvent.getY();
            dragStartX = x;
            dragStartY = y;
            AnchorPane.setLeftAnchor(selectRec, dragStartX);
            AnchorPane.setTopAnchor(selectRec, dragStartY);
        });
        // 开启拖拽
        anchorPane.setOnDragDetected(mouseEvent -> anchorPane.startFullDrag());
        anchorPane.setOnMouseDragOver(mouseDragEvent -> {
            double x = mouseDragEvent.getX();
            double y = mouseDragEvent.getY();
            double width = x - dragStartX;
            double height = y - dragStartY;
            selectRec.setHeight(height);
            selectRec.setWidth(width);
        });
        anchorPane.setOnMouseDragExited(mouseDragEvent -> {
            dragEndY = mouseDragEvent.getY();
            dragEndX = mouseDragEvent.getX();
            Button button = new Button("完成");
            anchorPane.getChildren().add(button);
            AnchorPane.setTopAnchor(button, dragEndY + button.getHeight());
            AnchorPane.setLeftAnchor(button, dragEndX);
            button.setOnMouseClicked(mouseEvent -> {
                ControllerUtils.closePane(anchorPane);
                getScreenImg();
                // 关闭截图窗口
                ControllerUtils.closePane(anchorPane);
//                 还原主窗口
                GlobalVar.getMainStage().setIconified(false);
//                 还原 action 窗口
                ((Stage) root.getScene().getWindow()).setIconified(false);
            });

        });

    }

    public void getScreenImg() {
        double width = dragEndX - dragStartX;
        double height = dragEndY - dragStartY;
        Rectangle rectangle = new Rectangle((int) dragStartX, (int) dragStartY, (int) width, (int) height);
//        findGraph = backgroundGraph.getSubimage((int) dragStartX, (int) dragStartY, (int) width, (int) height);
        findGraph = new Screen().capture(rectangle).getImage();
//        BufferedImage bufferedImage = FindImg.screenCapture(rectangle);
//        screenGraph = bufferedImage;
        WritableImage image = SwingFXUtils.toFXImage(findGraph, null);
        imgView.setImage(image);
    }

    public String imgToBase64String(BufferedImage bufferedImage) {
        final ByteArrayOutputStream os = new ByteArrayOutputStream();
        try (final OutputStream b64os = Base64.getEncoder().wrap(os)) {
            ImageIO.write(bufferedImage, "png", b64os);
        } catch (final IOException ioe) {
            System.out.println("image to base64 格式转换错误" + ioe);
            throw new UncheckedIOException(ioe);
        }
        return os.toString();
    }


}
